<template>
    <!-- 搜索相关 start -->
    <el-form :model="queryParams" ref="refForm" size="default" :inline="true" label-width="38px">
        <el-form-item label="人员" prop="user" label-width="58px">
            <el-select v-model="queryParams.userId" placeholder="请选择人员" clearable style="width: 120px">
                <el-option v-for="(item, index) in userOptions" :key="index" :label="item.name"
                    :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="任务状态" prop="status" label-width="88px">
            <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable style="width: 150px">
                <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.statusDes"
                    :value="item.status"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="任务类别" prop="taskType" label-width="68px">
            <el-select v-model="queryParams.taskType" placeholder="请选择任务类别" clearable style="width: 150px">
                <el-option v-for="(item, index) in taskTypeOptions" :key="index" :label="item.label"
                    :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="记忆日期" prop="rememberStartDate" label-width="108px">
            <el-date-picker v-model="queryParams.rememberStartDate" placeholder="请选择记忆日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" :style="{ width: '100%' }" clearable>
            </el-date-picker>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleGetList">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetForm(refForm)">重置</el-button>
        </el-form-item>
    </el-form>
    <!-- 搜索相关 end -->

    <!-- 表格相关 start -->
    <el-table :data="filterTableData" style="height: 550px;">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="55" :index="indexMethod" />
        <el-table-column label="人员" prop="userName" width="70" />
        <el-table-column label="标题" prop="title" width="120" show-overflow-tooltip />
        <el-table-column label="内容" prop="content" width="120" show-overflow-tooltip />
        <el-table-column label="任务类别" prop="taskType" width="80" />
        <el-table-column label="任务状态" prop="status" width="100">
            <!-- <template #default="scope">
                <span :style="{ backgroundColor: getStatusBackgroundColor(scope.row.status), 
                    color: getStatusColor(scope.row.status) }">{{ scope.row.status }}</span>
            </template> -->
            <template #default="scope">
                <el-button :type="getStatusType(scope.row.status)" size="small" :disabled="true">
                    {{ scope.row.status }}</el-button>
            </template>
        </el-table-column>
        <el-table-column label="记忆日期" prop="rememberDate" width="100" />
        <el-table-column label="备注" prop="remark" width="100" show-overflow-tooltip />
        <el-table-column width="150">
            <template #header>
                <el-input v-model="search" size="default" placeholder="Type to search" />
            </template>
            <template #default="scope">
                <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
                    icon-color="#626AEF" title="确定完成此任务么？" @confirm="confirmEvent(scope.$index, scope.row)">
                    <template #reference>
                        <el-button size="small" type="success">完成任务</el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100, 200, 300, 400]" :small="small" :background="background"
        layout="total, sizes, prev, pager, next, jumper" :total=pageData.totalNum @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="margin-top: 20px;" />
    <!-- 表格相关 end -->
</template>
<script setup lang='ts'>
import { computed, ref, reactive, onMounted } from 'vue'
import { showErrorMsg, showSuccessMsg, resetForm, indexMethod, getNowDate } from '@/api/common';
import { getUserInfo } from "@/utils/auth";
import type { FormInstance } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { page, finishTask } from "@/api/dailyPlan/dailyTask";
import { listAll } from "@/api/user/user";
import type { DailyTask, QueryParams } from '@/api/dailyPlan/dailyTask';
import type { ApiResponse, PageResponse, OnlyIdRequest, PageData } from '@/api/common';
import type { User } from '@/api/user/user'; 
const refForm = ref<FormInstance>()
const small = ref(false)
const background = ref(true)
interface Status {
    status: number,
    statusDes: string,
}
let onlyIdRequest = reactive<OnlyIdRequest>({
    id: null,
})
let taskTypeOptions = ref(
    [{
        "label": "记忆任务",
        "value": 0
    }, {
        "label": "定时任务",
        "value": 1
    }],
)
let statusOptions = ref<Status[]>([
    {
        status: 0,
        statusDes: '未完成',
    },
    {
        status: 1,
        statusDes: '已完成',
    }
]);
let userOptions = reactive<User[]>([]);
let queryParams = reactive<QueryParams>({
    pageNum: 1,
    pageSize: 10,
    userId: null,
    status: 0,
    taskType: 0,
    rememberStartDate: getNowDate(),
})
let pageData = reactive<PageData<DailyTask>>({
    totalNum: 0,
    tableData: [],
})
const search = ref('')
const filterTableData = computed(() =>
    pageData.tableData.filter(
        (data) =>
            !search.value ||
            data.title.toLowerCase().includes(search.value.toLowerCase()) ||
            data.content.toLowerCase().includes(search.value.toLowerCase())
    )
)
const handleGetList = () => {
    page(queryParams).then((res: ApiResponse<PageResponse<DailyTask>>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            let totalTemp = parseInt(res.data.total);
            pageData.totalNum = totalTemp;
            pageData.tableData = res.data.records;
        }
    });
}
const handleSizeChange = (newSize: number) => {
    console.log(`${newSize} items per page`)
    queryParams.pageSize = newSize;
    handleGetList();
}
const handleCurrentChange = (newPage: number) => {
    console.log(`current page: ${newPage}`)
    queryParams.pageNum = newPage;
    handleGetList();
}
onMounted(() => {
    // 查询所有人员
    listAll().then((res: ApiResponse<User[]>) => {
        // 这种直接赋值的方式，会破坏Vue 的响应式系统
        // userOptions = response.data
        // 使用数组的 push 方法来更新 userOptions
        // userOptions.splice(0, userOptions.length, ...response.data);
        // 这两种方式都可以。
        let userList = res.data;
        userOptions.push(...userList);
        if (userList.length == 1) {
            queryParams.userId = userList[0].id;
        }
    })
    // 查询所有计划
    // handleGetList();
})
const confirmEvent = (index: number, row: DailyTask) => {
    onlyIdRequest.id = row.id;
    finishTask(onlyIdRequest).then((res: ApiResponse<string>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            showSuccessMsg('任务成功完成！');
            handleGetList();
        }
    })
}
const getStatusType = (status: string) => {
    if (status === '未完成') {
        return 'warning';
    } else if (status === '已完成') {
        return 'success';
    } else {
        return 'info'; // Default type
    }
}
onMounted(() => {
    const userInfo = getUserInfo();
    queryParams.userId = userInfo.id;
})
</script>
<style scoped></style>